import {Label, Text} from '@kintone/kintone-ui-component/esm/js';
import * as qcc from '../api/QichachaAPI';
import {BaseConfig} from './BaseConfig';
import util from '../common/util';

export class QichachaConfig extends BaseConfig {
  constructor({pluginConfig, proxyConfig}) {
    super({
      pluginConfig,
      proxyConfig,
      server: qcc.SERVER,
      tableCells: qcc.API_RETURN_FIELD
    });
    this.qichachaAppKey = new Text({
      placeholder: 'KEY',
      value: `${qcc.SERVER.ID}_authKey` in this.pluginConfig ? this.pluginConfig[`${qcc.SERVER.ID}_authKey`] : ''
    });
    this.qichachaSecretKey = new Text({
      placeholder: '密钥',
      value: `${qcc.SERVER.ID}_secretKey` in this.pluginConfig ? this.pluginConfig[`${qcc.SERVER.ID}_secretKey`] : ''
    });
  }

  render() {
    const div = super.render();

    const authDiv = this.divElements[0];

    const keyDiv = document.createElement('div');
    keyDiv.className = 'company-info_pb_10 company-info_display_flex';
    keyDiv.appendChild(new Label({text: '企查查接口Key ', isRequired: true}).render());
    keyDiv.appendChild(this.qichachaAppKey.render());
    const secretKeyDiv = document.createElement('div');
    secretKeyDiv.className = 'company-info_display_flex';
    secretKeyDiv.appendChild(new Label({text: '企查查接口密钥', isRequired: true}).render());
    secretKeyDiv.appendChild(this.qichachaSecretKey.render());
    authDiv.appendChild(keyDiv);
    authDiv.appendChild(secretKeyDiv);

    return div;
  }

  checkValue() {
    if (util.isEmptyString(this.qichachaAppKey.getValue())) {
      return '请填写 "企查查接口Key"';
    }

    if (util.isEmptyString(this.qichachaSecretKey.getValue())) {
      return '请填写 "企查查接口密钥"';
    }

    return super.checkValue();
  }

  buildNewConfigValue() {
    const newConfigValue = {};

    newConfigValue[`${qcc.SERVER.ID}_authKey`] = this.qichachaAppKey.getValue();
    newConfigValue[`${qcc.SERVER.ID}_secretKey`] = this.qichachaSecretKey.getValue();

    return {
      ...newConfigValue,
      ...super.buildNewConfigValue()
    };
  }
}